package org.example.Backtracking_algorithm;

import java.util.*;
import java.util.stream.Collectors;

public class Permutations {
    public static List<List<Integer>> result = new ArrayList<>();
    public static LinkedList<Integer> value = new LinkedList<>();
    public static void main(String[] args) {
        //全排列

        //给定一个不含重复数字的数组 nums ，返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
        int[] nums = {1,2,3};
        permute(nums);
        prin();
    }
    //第一种方法
    public static List<List<Integer>> permute(int[] nums) {
        List<Integer> arrayList = Arrays.stream(nums).boxed().collect(Collectors.toList());
        get(arrayList,nums.length);
        return result;
    }
    public static void get(List<Integer> arrayList,int len){
        if (value.size()==len || arrayList.size()==0){
            result.add(new ArrayList<>(value));
            return;
        }
        for (int i = 0; i < arrayList.size(); i++) {
            ArrayList<Integer> list = new ArrayList<>(arrayList);
            value.add(list.get(i));
            list.remove(i);
            get(list,len);
            value.removeLast();
        }
    }
    //第二种方法
    public static List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        get(nums, used);
        return result;
    }

    public static void get(int[] nums, boolean[] used) {
        if (value.size() == nums.length) {
            result.add(new ArrayList<>(value));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i] || (i > 0 && nums[i - 1] == nums[i])) continue;
            value.add(nums[i]);
            used[i] = true;
            get(nums, used);
            used[i] = false;
            value.removeLast();
        }
    }
    public static void prin(){
        for (List<Integer> list : result) {
            System.out.print("[ ");
            for (Integer integer : list) {
                System.out.print(integer+" ");
            }
            System.out.print(" ]");
        }
        System.out.println();
    }
}
